package com.mediacloud.app.newsmodule.fragment

import android.os.Build
import android.text.TextUtils
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.alibaba.fastjson.JSON
import com.blankj.utilcode.util.NetworkUtils
import com.eventTrack.TXReportManager
import com.mediacloud.app.fbnavsk.SecondNav
import com.mediacloud.app.fbnavsk.navPaddingTopMatch
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.ArticleListData
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.nav2.fragment.HqyNavFragment
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.fragment.video.x.RVListVideoKit
import com.mediacloud.app.newsmodule.utils.BindEventBus
import com.mediacloud.app.newsmodule.utils.VideoAddressGet
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig
import com.mediacloud.app.reslib.enums.ToolBarActionF5OrTop
import com.mediacloud.app.reslib.enums.XKey
import com.mediacloud.app.reslib.util.DataInvokeUtil
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import com.tencent.mmkv.MMKV
import com.utils.ExposurePoolService
import com.yoake.media.player.utils.XVideoBitRate
import com.yoake.media.player.utils.XVideoItem
import com.yoake.media.player.utils.cache.XPlayerPreloadManager
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_info_flow.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class InfoFlowFragment : HqyNavFragment(), OnRefreshLoadMoreListener,
    ToolBarActionF5OrTop {
    //private var mVideoListPlayerUtil: VideoListPlayerUtil? = null
    var smallSize = 4
    var multiple = 3 //倍数
    var catalogID: String? = null
    private var catalogItem: CatalogItem? = null
    val tempList: MutableList<Any> = ArrayList()

    private var pageSize = 20
    private var adapter: InfoFlowAdapter? = null
    private var second_catalog_id = ""
    private var second_model = ""

    private var mRVListVideoKit: RVListVideoKit? = null


    private var preLoadKit: ListPreLoadKit<InfoFlowItem>? = null

    override fun getLayoutResID(): Int {
        return R.layout.fragment_info_flow
    }

    override fun initArgs() {
        super.initArgs()
        if (fragmentArguments != null) {
            saveInstanceArguments = fragmentArguments
            catalogID = saveInstanceArguments?.getString("id")
            catalogItem = saveInstanceArguments?.getParcelable("catalog")
        } else if (saveInstanceArguments != null) {
            catalogID = saveInstanceArguments!!.getString("id")
            catalogItem = saveInstanceArguments!!.getParcelable("catalog")
        }
    }

    override fun initView() {
        navPaddingTopMatch()
        loadingView = findViewById(R.id.mLoadingView);
        initStateView();
        retryTips?.setOnClickListener {
            if (currentState != TYPE_LOADING) {
                if(NetworkUtils.isConnected()) {
                    showStateView(TYPE_LOADING, false)
                    onRefresh(refreshLayout)
                }
            }
        }
        showStateView(TYPE_LOADING, false)
        refreshLayout.setOnRefreshLoadMoreListener(this)
        val itemAnimator = recyclerView.itemAnimator
        if( itemAnimator is SimpleItemAnimator){
            itemAnimator .supportsChangeAnimations = false
        }

        var lastVisibleItem: Int = 0
        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                val layoutManager = recyclerView.layoutManager
                layoutManager?.let {
                    if (layoutManager is GridLayoutManager) {
                        lastVisibleItem = layoutManager.findLastVisibleItemPosition()
                    } else if (layoutManager is LinearLayoutManager) {
                        lastVisibleItem = layoutManager.findLastVisibleItemPosition()
                    }
                    if (lastVisibleItem == it.itemCount - 1) {
                        preLoadKit?.onLoadMore()
                    }
                }
            }

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if(newState == RecyclerView.SCROLL_STATE_IDLE){
                    app_jhapp_video_imp()
                }
            }
        })

        preLoadKit = object : ListPreLoadKit<InfoFlowItem>(requireContext(), refreshLayout) {
            override fun onSetData(data: InfoFlowItem) {
                setData(data)
            }

            override fun onPreload(preNum: Int) {
                preload(preNum)
            }

        }
        adapter = InfoFlowAdapter(requireContext())
        adapter?.catalogItem = catalogItem
        refreshLayout.setOnRefreshLoadMoreListener(this)
        refreshLayout.setEnableLoadMore(false)
        recyclerView.layoutManager = GridLayoutManager(requireContext(), 2)
        recyclerView.adapter = adapter
        recyclerView.isNestedScrollingEnabled = false;
        recyclerView.setHasFixedSize(false);
        recyclerView.isFocusable = false;

        mRVListVideoKit = RVListVideoKit(requireContext(), recyclerView,this)
        parentFragment?.let {
            if (it is SecondNav) {
                mRVListVideoKit?.playerView?.viewPlayer = it.viewPager
            }
        }
        BindEventBus(this,adapter)
    }

    //private var pendingIndex = -1;
    override fun onLoadMore(refreshLayout: RefreshLayout) {
        Log.w(ListPreLoadKit.LTAG, "触发了 RefreshLayout onLoadMore")
        preLoadKit?.getMoreDate()
    }


    override fun choosed() {
        super.choosed()
        recyclerView?.postDelayed({
            mRVListVideoKit?.pendingStopPlay = false
            mRVListVideoKit?.mDy=1
            mRVListVideoKit?.initPendingPlay()
        },800)
        if(isAdded){
            app_jhapp_video_imp()
        }
    }

    override fun onResume() {
        super.onResume()
    }

    override fun initToRefresh() {
        if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
            return
        }
        DataInvokeUtil.getContentListResult(catalogID, 1, 1, null)
            .subscribe(
                {
                    if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                        return@subscribe
                    }
                    it.body()?.optJSONObject("data")?.optJSONObject("navigate")?.let {
                        second_catalog_id = it.optString("second_catalog_id")
                        second_model = it.optString("second_model")
                        smallSize = it.optInt("staggered_page")
                        pageSize = smallSize * multiple
                    }
                    getDate()
                },
                {
                    if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                        return@subscribe
                    }
                    if (it != null) {
                        showStateView(TYPE_NET_NOT_GIVE_FORCE, false)
                    } else {
                        showStateView(TYPE_NO_CONTENT, false)
                    }
                }
            )

    }

    override fun unChosoed() {
        super.unChosoed()
        mRVListVideoKit?.stopPlay()
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        preLoadKit?.onRefresh()
        mRVListVideoKit?.reset()
        getDate()
    }

    // var nextInfoFlowSmallAtLeft = true
    private fun getDate() {
        val map = hashMapOf<String,Any>()
        map["catalog_id"] = second_catalog_id
        map["type"] = second_model
        map["page"] = preLoadKit!!.pageNum
        map["perPage"] = multiple
        map["client"] = "android"
        val observable1 =
            DataInvokeUtil.getContentList(catalogID, preLoadKit!!.pageNum, pageSize, null)
        val observable2 =
            DataInvokeUtil.ziMeiTiApi.getCMSList(map)

        val d = Observable.zip(
            observable1,
            observable2
        ) { t1, t2 ->
            val item = InfoFlowItem()
            if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                item
            } else {
                val smallList: MutableList<ArticleItem> = ArrayList()
                if (t1.isSuccessful) {
                    val temp = ArticleListData()
                    temp.readFromJson(t1.body())
                    item.componentItems = temp.componentItems
                    smallList.addAll(temp.articleList)
                    preLoadKit?.hasMore = temp.more
                }
                val bigList: MutableList<ArticleItem> = ArrayList()
                if (t2.isSuccessful) {
                    val state = t2.body()?.optBoolean("state")
                    if (state == true) {
                        val data = t2.body()?.optJSONObject("data")
                        data?.optJSONArray("meta")?.let {
                            val size = it.length()
                            for (i in 0 until size) {
                                val jsonObj = it.optJSONObject(i);
                                val articleItem =
                                    JSON.parseObject("" + jsonObj, ArticleItem::class.java)
                                articleItem.infoFlowBig = 1

                                try {
                                    val video: org.json.JSONObject =
                                        org.json.JSONObject(jsonObj.optString("video"))
                                    val tsAddress = VideoAddressGet.getAddress(video)
                                    val videoPlayObj = XVideoItem(articleItem.getTitle())
                                    val cdnEncypt = video.optString("cdnConfigEncrypt")
                                    videoPlayObj.cdnIv =
                                        AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_iv
                                    videoPlayObj.cdnKey =
                                        AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_key
                                    for (i in 0 until tsAddress.length()) {
                                        val line = tsAddress.optJSONObject(i)
                                        val lineItem = XVideoBitRate()
                                        lineItem.path = line.optString("url")
                                        lineItem.title = line.optString("title")
                                        lineItem.cdnEncypt = cdnEncypt
                                        videoPlayObj.bitRates.add(lineItem)
                                    }

                                    val iterator = videoPlayObj.bitRates.iterator()
                                    while (iterator.hasNext()) {
                                        val v = iterator.next()
                                        if (v.title?.contains("源码") == true) {
                                            iterator.remove()
                                        }
                                    }
                                    videoPlayObj.bitRates.reverse()
                                    if (videoPlayObj.bitRates.size > 0) {
                                        val bitRates = videoPlayObj.bitRates
                                        val size = bitRates.size
                                        var tempBitRate: XVideoBitRate? = null
                                        for (i in 0 until size) {
                                            if ("${bitRates[i].title}".uppercase().contains("1080P")) {
                                                tempBitRate = bitRates[i]
                                                break
                                            }
                                        }
                                        if (tempBitRate == null) {
                                            tempBitRate = bitRates[size - 1]
                                        }
                                        XPlayerPreloadManager.getInstance(context).addPreloadTask(tempBitRate.path)
                                        articleItem.xVideoItem = videoPlayObj
                                    }

                                } catch (e: Exception) {
                                    e.printStackTrace()
                                }

                                bigList.add(articleItem)
                            }
                        }
                        val lastPage = data?.optJSONObject("paging")?.optInt("lastPage") ?: 0
                        preLoadKit?.apply {
                            hasMore = hasMore || pageNum < lastPage
                        }
                    }
                }


                if (smallList.isNotEmpty() && bigList.isNotEmpty()) {
                    val size = smallList.size
                    for (i in 0 until size) {
                        if (i % smallSize == 0 && bigList.isNotEmpty()) {
                            item.articleList.add(bigList.removeAt(0))
                        }
                        item.articleList.add(smallList[i])
                    }
                    item.articleList.addAll(bigList)
                } else if (smallList.isEmpty()) {
                    //没小图了就添加所有大图
                    item.articleList.addAll(bigList)
                } else if (bigList.isEmpty()) {
                    //同理
                    item.articleList.addAll(smallList)
                }
                item
            }
        }.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<InfoFlowItem> {
                override fun onSubscribe(d: Disposable) {}

                @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
                override fun onNext(t: InfoFlowItem) {
                    if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                        return
                    }
                    refreshLayout.finishRefresh()
                    refreshLayout.finishLoadMore()
                    preLoadKit?.preLoadData?.add(t)

                    if (preLoadKit?.pageNum == 1) {
                        MMKV.defaultMMKV()
                            .putString(XKey.CACHE_INFO_FLOW + catalogID, JSON.toJSONString(t))
                    }

                    setData(t)
                    dataReady = true
                    if (hadChoosed) {
                        app_jhapp_video_imp()
                    }
                    if (preLoadKit?.hasMore == true) {
                        preLoadKit?.preload()
                    } else {
                        refreshLayout.finishLoadMoreWithNoMoreData()
                    }
                    try {
                        recyclerView.postDelayed({
                            if (userVisibleHint || !hidden) {
                                mRVListVideoKit?.let {
//                                    if(it.pendingStopTimeStamp == 0L){//说明还没有切走
//                                        try {
//                                            mRVListVideoKit?.initPendingPlay()
//                                        }catch (e:Exception){
//                                            e.printStackTrace()
//                                        }
//                                    }
                                    try {
                                        mRVListVideoKit?.initPendingPlay()
                                    }catch (e:Exception){
                                        e.printStackTrace()
                                    }
                                }
                            }

                        }, 1000)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                    closeStateView()
                }

                override fun onError(e: Throwable) {
                    if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                        return
                    }
                    refreshLayout.finishRefresh(false)
                    refreshLayout.finishLoadMore()
                    val cacheString =
                        MMKV.defaultMMKV().getString(XKey.CACHE_INFO_FLOW + catalogID, "")
                    if (!TextUtils.isEmpty(cacheString)) {
                        val t = JSON.parseObject(cacheString, InfoFlowItem::class.java)
                        closeStateView()
                        setData(t)
                    } else {
                        showStateView(TYPE_NET_NOT_GIVE_FORCE, false)
                    }


                }

                override fun onComplete() {

                }
            })
    }


    private fun setData(t: InfoFlowItem) {
        if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
            return
        }
        if (t.articleList!=null&&t.articleList.size>0){
            for (i in 0 until t.articleList.size){
                TXReportManager.getInstance()?.pickedIds?.add(t.articleList.get(i)?.id)
            }
        }
        if (t.article!=null){
            TXReportManager.getInstance()?.pickedIds?.add(t.article?.id)
        }
        tempList.clear()
        if (preLoadKit!!.pageNum == 1) {
            t.componentItems?.let {
                tempList.addAll(it)
            }
            tempList.addAll(t.articleList)
            adapter?.setItems(tempList)
        } else {
            tempList.addAll(t.articleList)
            adapter?.addItems(tempList)
        }

    }

    private fun preload(preNum: Int) {

        val observable1 =
            DataInvokeUtil.getContentList(catalogID, preNum, pageSize, null)
        val map = hashMapOf<String,Any>()
        map["catalog_id"] = second_catalog_id
        map["type"] = second_model
        map["page"] = preNum
        map["perPage"] = multiple
        map["client"] = "android"
        val observable2 =
            DataInvokeUtil.ziMeiTiApi.getCMSList(map)

        val d = Observable.zip(
            observable1,
            observable2
        ) { t1, t2 ->
            val item = InfoFlowItem()
            val smallList: MutableList<ArticleItem> = ArrayList()
            if (t1.isSuccessful) {
                val temp = ArticleListData()
                temp.readFromJson(t1.body())
                item.componentItems = temp.componentItems
                smallList.addAll(temp.articleList)
                preLoadKit?.hasMore = temp.more
            }
            val bigList: MutableList<ArticleItem> = ArrayList()
            if (t2.isSuccessful) {
                val state = t2.body()?.optBoolean("state")
                if (state==true) {
                    val data = t2.body()?.optJSONObject("data")
                    data?.optJSONArray("meta")?.let {
                        val size = it.length()
                        for (i in 0 until size) {
                            val jsonObj = it.optJSONObject(i);
                            val articleItem =
                                JSON.parseObject("" + jsonObj, ArticleItem::class.java)
                            articleItem.infoFlowBig = 1

                            try {
                                val video: org.json.JSONObject =
                                    org.json.JSONObject(jsonObj.optString("video"))
                                val tsAddress = VideoAddressGet.getAddress(video)
                                val videoPlayObj = XVideoItem(articleItem.getTitle())
                                val cdnEncypt = video.optString("cdnConfigEncrypt")
                                videoPlayObj.cdnIv =
                                    AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_iv
                                videoPlayObj.cdnKey =
                                    AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_key
                                for (i in 0 until tsAddress.length()) {
                                    val line = tsAddress.optJSONObject(i)
                                    val lineItem = XVideoBitRate()
                                    lineItem.path = line.optString("url")
                                    lineItem.title = line.optString("title")
                                    lineItem.cdnEncypt = cdnEncypt
                                    videoPlayObj.bitRates.add(lineItem)
                                }

                                val iterator = videoPlayObj.bitRates.iterator()
                                while (iterator.hasNext()) {
                                    val v = iterator.next()
                                    if (v.title?.contains("源码") == true) {
                                        iterator.remove()
                                    }
                                }
                                videoPlayObj.bitRates.reverse()
                                if (videoPlayObj.bitRates.size > 0) {
                                    XPlayerPreloadManager.getInstance(requireContext())
                                        .addPreloadTask(videoPlayObj.bitRates[0].path)
                                    articleItem.xVideoItem = videoPlayObj
                                }
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }

                            bigList.add(articleItem)
                        }
                    }
                    val lastPage = data?.optJSONObject("paging")?.optInt("lastPage") ?: 0

                    preLoadKit?.apply {
                        hasMore = hasMore || pageNum < lastPage
                    }
                }
            }
            if (smallList.isNotEmpty() && bigList.isNotEmpty()) {
                val size = smallList.size
                for (i in 0 until size) {
                    if (i % smallSize == 0 && bigList.isNotEmpty()) {
                        item.articleList.add(bigList.removeAt(0))
                    }
                    item.articleList.add(smallList[i])
                }
                item.articleList.addAll(bigList)
            } else if (smallList.isEmpty()) {
                //没小图了就添加所有大图
                item.articleList.addAll(bigList)
            } else if (bigList.isEmpty()) {
                //同理
                item.articleList.addAll(smallList)
            }
            item
        }.subscribeOn(Schedulers.io())
            .onErrorReturn { null }
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<InfoFlowItem> {
                override fun onSubscribe(d: Disposable) {
                }

                override fun onNext(t: InfoFlowItem) {
                    preLoadKit?.onPreloadSuccess(t, preNum)
                }

                override fun onError(e: Throwable) {
                    preLoadKit?.onPreloadFail(preNum)
                }

                override fun onComplete() {
                }
            })
    }


    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (!userVisibleHint) {
            mRVListVideoKit?.stopPlay()
        }else{
            recyclerView?.postDelayed({
                mRVListVideoKit?.pendingStopPlay = false
                mRVListVideoKit?.initPendingPlay()
            },800)
            recyclerView?.postDelayed({
                app_jhapp_video_imp()
            },1500)
        }
    }



    var hidden: Boolean = true;
    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        this.hidden = hidden
        if (hidden) {
            mRVListVideoKit?.stopPlay()
        }
    }

    override fun onDestroy() {
        mRVListVideoKit?.onDestroy()
        adapter?.destroy()
        super.onDestroy()
    }

    override fun onDestroyView() {
        refreshLayout?.setOnRefreshLoadMoreListener(null)
        super.onDestroyView()
    }


    override fun f5() {
        if (recyclerView.childCount > 0) {
            recyclerView.scrollToPosition(0)
            refreshLayout.setEnableRefresh(true)
            refreshLayout.autoRefresh(200)
        }
    }

    override fun gun() {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onNotIntrest(event: NotIntrestEvent) {
        val list = adapter?.articleItems
        list?.let{
            for (i in it.indices) {
                if (i<list.size && it[i] is ArticleItem){
                    if ((it[i] as ArticleItem).id == event.id) {
                        list.remove(it[i])
                        adapter?.notifyDataSetChanged()
                    }
                }

            }
        }

    }
    private var dataReady = false
    private val app_jhapp_video_impRunable :Runnable= Runnable {
        ExposurePoolService.getExecutorService().execute{
            try {
                val childCount = recyclerView.childCount
                for (i in 0 until childCount){
                    val view = recyclerView.getChildAt(i)
                    val position = recyclerView.getChildAdapterPosition(view)
                    val obj:Any? = adapter?.articleItems?.get(position)
                    if(obj is ArticleItem){
                        TXReportManager.getInstance().app_jhapp_video_imp(
                            catalogItem?.name,
                             obj,
                            i
                        )
                    }
                }

            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun app_jhapp_video_imp() {
        if (!dataReady) return
        recyclerView?.apply {
            removeCallbacks(app_jhapp_video_impRunable)
            postDelayed(app_jhapp_video_impRunable, TXReportManager.EXPOSURE_DELAY)
        }

    }
}